<template>
  <div>
    <div class="header">
      <span class="header-title">基础信息管理</span>
      <span class="divider">|</span>
      <span class="sub-title">灾害点信息管理</span>
    </div>

    <div class="control-panel">
      <el-row>
        <!-- 城市选择 -->
        <el-col :span="2">
          <el-select v-model="city" placeholder="全市" class="control-item">
            <el-option label="全市" value=""></el-option>
            <el-option label="雨城" value="雨城"></el-option>
            <el-option label="名山" value="名山"></el-option>
            <el-option label="经开" value="经开"></el-option>
            <el-option label="天全" value="天全"></el-option>
            <el-option label="芦山" value="芦山"></el-option>
            <el-option label="宝兴" value="宝兴"></el-option>
            <el-option label="荥经" value="荥经"></el-option>
            <el-option label="汉源" value="汉源"></el-option>
            <el-option label="石棉" value="石棉"></el-option>
          </el-select>
        </el-col>
         
        <el-col v-if="city && city !== ''" :span="2">
          <el-select v-model="town1" placeholder="请选择乡镇" class="control-item">
            <el-option v-for="option in townOptions" :key="option.name" :label="option.label" :value="option.label" />
          </el-select>
        </el-col>

        <!-- 隐患类型选择 -->
        <el-col :span="2">
          <el-select v-model="hazardType" placeholder="全部类型" class="control-item">
            <el-option label="全部类型" value=""></el-option>
            <el-option label="地质灾害" value="地质灾害"></el-option>
            <el-option label="山洪灾害" value="山洪灾害"></el-option>
          </el-select>
        </el-col>

        <!-- 隐患点数量 -->
        <el-col :span="3">
          <span class="hazard-count">隐患点数量: {{ hazardCount }}个</span>
        </el-col>

        <!-- 类型搜索 -->
        <el-col :span="2">
          <el-select v-model="searchType" placeholder="隐点名字" class="control-item">
            <el-option label="隐患点名字" value="隐患点名字"></el-option>
            <el-option label="编号" value="编号"></el-option>
            <el-option label="乡镇" value="乡镇"></el-option>
          </el-select>
        </el-col>

        <!-- 查询 -->
        <el-col :span="5">
          <el-input v-model="hazardName" placeholder="" class="control-item"></el-input>
        </el-col>

        <!-- 查询按钮 -->
        <el-col :span="2">
          <el-button @click="searchHazards" type="primary" class="control-item">查询</el-button>
        </el-col>

        <!-- 显示全部按钮 -->
        <el-col :span="2">
          <el-button @click="showAll" type="default" class="control-item">显示全部</el-button>
        </el-col>

        <!-- 新增 -->
        <el-col :span="2">
          <el-button @click="openAddHazardDialog" type="default" class="control-item">新增隐患点</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 表格区域 -->
    <div>
      <el-table class="product" :data="groupData" stripe style="width: 100%" :header-cell-style="headerCellStyle"
        :cell-style="cellStyle" :row-style="rowStyle">
        <el-table-column
          v-for="column in columns"
          :key="column.prop"
          :prop="column.prop"
          :label="column.label"
          :min-width="column.minWidth || '12%'"
          :fixed="column.fixed || ''">
        </el-table-column>

        <el-table-column prop="operate" label="操作" min-width="30%">
          <template slot-scope="scope">
            <el-button type="info" size="small" class="operation-button" @click="openEditHazardDialog(scope.row)">编辑</el-button>
            <el-button type="primary" size="small" class="operation-button" @click="deleteHazard(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增隐患点弹窗 -->
    <el-dialog :visible.sync="dialogVisible" width="60%">
      <el-form :model="newHazardForm" label-width="120px" :rules="formRules">
        <el-form-item label="隐患点编号" prop="dsid">
          <el-input v-model="newHazardForm.dsid" size="small" style="width: 150px;"></el-input>
          <span class="input-help">编号唯一，无法更改，如需更改请删除后新建</span>
        </el-form-item>

        <el-form-item label="隐患点名称" prop="dsname">
          <el-input v-model="newHazardForm.dsname" size="small" style="width: 200px;"></el-input>
        </el-form-item>

        <el-form-item label="隐患类型" prop="type">
          <el-select v-model="newHazardForm.type" size="small" style="width: 150px;">
            <el-option label="地质灾害" value="地质灾害"></el-option>
            <el-option label="山洪灾害" value="山洪灾害"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="省" prop="province">
          <el-select v-model="newHazardForm.province" size="small" style="width: 100px;">
            <el-option label="四川省" value="四川省"></el-option>
          </el-select>
        </el-form-item>
         
        <el-form-item label="市" prop="province">
          <el-select v-model="newHazardForm.city" size="small" style="width: 100px;">
            <el-option label="雅安" value="雅安"></el-option>
          </el-select>
        </el-form-item>

         <!-- 区县 -->
         <el-form-item label="区县" prop="county">
            <el-select 
              v-model="newHazardForm.county" 
              size="small" 
              style="width: 150px;" 
              @change="onCountyChange">
              <el-option label="雅安" value="雅安"></el-option>
              <el-option label="雨城" value="雨城"></el-option>
              <el-option label="名山" value="名山"></el-option>
              <el-option label="经开" value="经开"></el-option>
              <el-option label="天全" value="天全"></el-option>
              <el-option label="芦山" value="芦山"></el-option>
              <el-option label="宝兴" value="宝兴"></el-option>
              <el-option label="荥经" value="荥经"></el-option>
              <el-option label="汉源" value="汉源"></el-option>
              <el-option label="石棉" value="石棉"></el-option>
            </el-select>
            <span class="input-help">隐患点所在区县</span>
              </el-form-item>

        <el-form-item label="乡镇" prop="town">
          <el-select v-model="newHazardForm.town" size="small" style="width: 150px;"  @change="onTownChange">
        <el-option
          v-for="option in townOptions"
          :key="option.name"
          :label="option.label"
          :value="option.label"
         >
        </el-option>
      </el-select>
          <span class="input-help">隐患点所在乡镇</span>
        </el-form-item>

        <!-- 村 -->
        <el-form-item label="村" prop="village">
          <el-input v-model="newHazardForm.village" size="small" style="width: 300px;"></el-input>
        </el-form-item>

        <!-- 街道 -->
        <el-form-item label="街道" prop="street">
          <el-input v-model="newHazardForm.street" size="small" style="width: 300px;"></el-input>
        </el-form-item>

        <el-form-item label="海拔" prop="altitude">
          <el-input v-model="newHazardForm.altitude" size="small" style="width: 100px;"></el-input>米
        </el-form-item>

        <el-form-item label="经度" prop="lon">
          <el-input v-model="newHazardForm.lon" size="small" style="width: 100px;"></el-input>度
        </el-form-item>

        <el-form-item label="纬度" prop="lat">
          <el-input v-model="newHazardForm.lat" size="small" style="width: 100px;"></el-input>度
        </el-form-item>
         
        <!-- <el-form-item label="更改关联人员" prop="lat">
          <el-transfer
          class="custom-transfer"
          v-model="selectedPersons" 
          :data="personList"               
          :titles="['待选人员', '关联人员']" 
          :button-texts="['取消关联', '加入']"  />
          <span class="input-help" >请至少选择1个关联责任人(建议乡镇长、村长、监测员均关联)；人员根据所选乡镇变化,如关联人员不在待选人员框,请到预警接收管理新增用户</span>
        </el-form-item> -->
        <!-- <el-form-item label="目前关联手机：" prop="phone">
      <span class="input-help" v-if="! telephones || telephones.length === 0">
        暂无关联人
      </span>
      <span class="input-help" v-else>
        {{ telephones.join(', ') }}
      </span>
     </el-form-item> -->
     </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">返回</el-button>
        <el-button type="primary" @click="submitNewUser">保存/更新</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Request from "@/utils/request";
import Cookies from "js-cookie";
import { setTabs } from "@/views/home/management/townList.js";
export default {
  data() {
    return {
      city: '',
      town1:'',
      hazardType: '',
      hazardName: '',
      hazardCount: '',
      searchType: '',
      columns: [
        { prop: 'dsid', label: '隐患点编号' },
        { prop: 'dsname', label: '隐患点名称' },
        { prop: 'type', label: '隐患类型' },
        { prop: 'altitude', label: '海拔' },
        { prop: 'lon', label: '经度' },
        { prop: 'lat', label: '纬度' },
        { prop: 'county', label: '区县',},
        { prop: 'town', label: '乡镇' },
        { prop: 'village', label: '村' },
        { prop: 'street', label: '街道' },
        { prop: 'editTime', label: '编辑时间' },
      ],
      groupData: [],
      dialogVisible: false,
      newHazardForm: {
        id: '',
        dsname: '',
        type: '',
        city:'',
        province:'',
        altitude: '',
        lon: '',
        lat: '',
        county: '',
        town: '',
        village: '',
        street: '',
        editTime: '',
        // telephones: [],
      },
      townOptions: [],
      formRules: {
        id: [
          { required: true, message: '编号不能为空', trigger: 'blur' },
        ],
        dsname: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        county: [
          { required: true, message: '请选择区县', trigger: 'change' }
        ],
        town: [
          { required: true, message: '请输入乡镇', trigger: 'blur' }
        ],
        lon: [
          { required: true, message: '经度不能为空', trigger: 'blur' }
        ],
        lat: [
          { required: true, message: '纬度不能为空', trigger: 'blur' }
        ],
      },
      selectedPersons: [],
      personList: [],
      editingHazard: null,
    };
  },
  mounted() {
    this.loadHazardData();
  },
  watch: {
    city(newCity) {
      this.onCityChange(); 
    },
  },
  methods: {
    
    onCityChange() {
      if (this.city) {
        this.town1 = ''; 
        this.townOptions = []; 
        this.townOptions = setTabs(this.city); 
      }
    },    // 监听区县变化，更新乡镇选项
    onCountyChange() {
      this.newHazardForm.town = ''; 
      this.townOptions = []; 
      this.townOptions = setTabs(this.newHazardForm.county); 
      this.checkAndFetchPersonList();
    },

    // 当乡镇改变时调用
    onTownChange() {
      this.checkAndFetchPersonList();
    },

    checkAndFetchPersonList() {
      if (this.newHazardForm.county && this.newHazardForm.town) {
        this.fetchPersonList();
      }
    },
    // 请求待选人员
  fetchPersonList() {
    const params = {
      county: this.newHazardForm.county, 
      town: this.newHazardForm.town, 
      type: Cookies.get('type'), 
    };

    Request.get('/newDisasterPoint/findUnSelectedPeople', { params })
      .then((response) => {
        if (response.data.code === 200) {
          // 更新待选人员列表
          this.personList = response.data.data.map((person, index) => ({
            key: String(index + 1), 
            label: person.town+'-'+person.featrueLabel+'-'+person.name, 
            telephones: person.telephones,
          }));
        } else {
          this.$message.error('未能获取待选人员');
        }
      })
      .catch((error) => {
        console.error('获取待选人员失败:', error);
        this.$message.error('请求失败');
      });
  },
    // 打开新增/编辑隐患点弹窗
    openAddHazardDialog() {
      this.editingHazard = null; 
      this.dialogVisible = true;
      this.resetForm();
    },

    // 打开编辑隐患点弹窗
    openEditHazardDialog(row) {
      this.editingHazard = row; 
      this.dialogVisible = true;
      this.newHazardForm = { ...row }; 
      this.checkAndFetchPersonList();
    },

    // 重置表单
    resetForm() {
      this.newHazardForm = {
        id: '',
        dsname: '',
        city:'',
        province: '',
        type: '',
        altitude: '',
        lon: '',
        lat: '',
        county: '',
        town: '',
        village: '',
        street: '',
        // telephones: [],
      };
    },

    // 保存或更新隐患点
    submitNewUser() {
      const apiUrl = this.editingHazard ? '/disasterPoint/update' : '/disasterPoint/add';
      const params = { ...this.newHazardForm };
       
      params.editTime = new Date().toISOString();

      if (this.editingHazard) {
        params.id = this.editingHazard.id; 
      }

      Request.post(apiUrl, { params })
        .then((response) => {
          if (response.data.code === 200) {
            this.$message.success('操作成功');
            this.loadHazardData();
            this.dialogVisible = false;
          } else {
            this.$message.error('操作失败');
          }
        })
        .catch((error) => {
          console.error('请求失败:', error);
          this.$message.error('请求失败');
        });
    },
    // 请求灾害点数据
    loadHazardData() {
      const params = {
        pageNum: 1,           
        pageSize: 99999,         
        city: this.city,
        town:this.town1,
        type: this.hazardType,
        condition: this.searchType, 
        content:this.hazardName,
      };
      Request.get('/disasterPoint/list', { params })
        .then(response => {
          if (response.data.code === 200) {
            this.groupData = response.data.data.list;
            this.hazardCount = response.data.data.total; 
            console.log(this.groupData); 
          } else {
            this.$message.error('请求失败');
          }
        })
        .catch(error => {
          console.error('请求失败:', error);
          this.$message.error('请求失败');
        });
    },
    
    // 查询按钮点击
    searchHazards() {
      this.loadHazardData();  
    },

    // 显示全部按钮点击
    showAll() {
      this.city = "";
      this.hazardType = "";
      this.hazardName = "";
      this.loadHazardData();  
    },
    // 删除隐患点
    deleteHazard(row) {
      this.$confirm('确定删除该隐患点?', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          id: row.id,  
        };

        Request.get('/disasterPoint/del', { params })
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('隐患点删除成功');
              this.loadHazardData(); 
            } else {
              this.$message.error('删除失败');
            }
          })
          .catch(error => {
            console.error('删除请求失败:', error);
            this.$message.error('请求失败');
          });
      }).catch(() => {
    console.log('用户取消了删除操作');
  });
    },
      
  
    // 表格样式
    headerCellStyle() {
      return {
        background: "#0c2340",
        color: "#fff",
      };
    },
    cellStyle() {
      return {
        background: "#05152e",
        color: "#fff",
      };
    },
    rowStyle() {
      return {
        height: "30px",
      };
    }
  }
}


</script>

<style lang="less">
.header {
  display: flex;
  align-items: center;
  padding: 10px;
  color: #fff;
}
.header-title {
  margin-right: 20px;
  font-weight: bold;
}
.divider {
  margin-right: 20px;
}
.sub-title {
  display: flex;
  align-items: center;
}

.control-panel {
  margin: 20px 0;
}
.control-item {
  width: 100%;
}
.el-col {
  margin-bottom: 10px;
  margin-right: 10px;
}
.hazard-count {
  font-size: 16px;
  color: #fff;
  line-height: 32px;
}
.operation-button {
  margin-left: 10px;
}
.control-item .el-input__inner {
  background-color: rgb(36, 54, 101);
  color: white;
  font-weight: bold;
  border: 2px solid #fff;
}
.input-help{
  margin-left: 20px;
}
.custom-transfer .el-transfer-panel {
  width: 250px; 
}
</style>
